<?php

declare(strict_types=1);

namespace app\admin\middleware;
use think\facade\Log;
use app\service\JwtSerice as JwtSerice;
use app\utils\Redis as RedisDB;

class CheckUser
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 获取Authorization
        $authAuthorization = $request->header('Authorization');
        if (!$authAuthorization || strpos($authAuthorization, 'Bearer ') != 0) {
            return error('请重新登录', '401');
        }
        try {
            // 获取token
            $token = str_replace('Bearer ', '', $authAuthorization);
            $info = JwtSerice::validateToken($token);
            // $cacheToken = cache('uid' . $info['uid']);
            $cacheToken = RedisDB::getKey("user", "token:$info[uid]");
            if ($info['exp'] > 0 && $cacheToken && $cacheToken == $info['token']) {
                $request->uid = $info['uid'];
                $request->token = $info['token'];
                $ttl = RedisDB::ttlKey("user", "token:$info[uid]");
                if ($ttl < 3300) {
                    JwtSerice::setToken($info['uid'], $info['token']);
                }
                return $next($request);
            } else {
                return error('请重新登录', '401');
            }
        } catch (\Throwable $e) {
            return error('请重新登录', '401');
        }
    }

}
